<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use addons\epay\library\Service as EpayService;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use addons\third\model\Third;
use think\Config;
use app\common\library\Auth;
use \app\admin\model\IncomeDetail;
use \app\admin\model\Region;
use \app\admin\model\Order;
use fast\Http;
use addons\third\library\Service;
/**
 * 个人中心接口
 */
class My extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        $this->token = $this->request->post('token');
        if ($this->request->action() == 'login' && $this->token) {
            $this->request->post(['token' => '']);
        }
        parent::_initialize();
    }  
    /**
     * 核销提货码
     * @ApiSummary  (核销提货码)
     * @ApiMethod   (POST)
     * @ApiParams   (name="code", type="string", required=true, description="核销提货码")
     */
    public function hexiao(){
        $user = $this->auth->getUser();
        $code = input('code');
        $order_detail = Order::get(['code'=>$code]);
        if($order_detail){

            $region_detail = Region::get($order_detail['region_id']);
            if($region_detail['user_id']!==$user->id)$this->error('您不是该地区的代理无法核销');

            if($order_detail['order_status']=='40')$this->error('该订单已核销了');

            $ratio = Config::get('site.ratio');

            $insert['total_price'] = $order_detail['total_price'];
            $insert['income'] = $order_detail['total_price']*$ratio;
            $insert['user_id'] = $user->id;
            $insert['order_id'] = $order_detail['id'];
            $insert['watch'] = 1;
            $insert['status'] = 1;

            $IncomeDetail = new IncomeDetail();//佣金明细
            $IncomeDetail->isUpdate(false)->save($insert);

            $region_detail->setInc('income',$insert['income']);

            $order_detail->save(['order_status'=>'40']);//修改订单状态为已核销

            $this->success('核销成功');

        }else{
            $this->error('数据找不到');
        }
    }

    /**
     * 小程序获取用户授权数据的接口
     * @ApiSummary  (小程序用户授权后把头像和昵称信息储存到数据库)
     * @ApiMethod   (POST)
     * @ApiParams   (name="openid", type="string", required=true, description="微信openid")
     * @ApiParams   (name="rawData", type="string", required=true, description="微信获取的rawData")
     */
    public function miniGetuserinfo()
    {
        $openid = $this->request->post("openid");
        $rawData = $this->request->post("rawData");
        if (!$rawData) {
            $this->error($rawData);
        }

        $rawData = htmlspecialchars_decode($rawData);
        $userInfo = (array)json_decode($rawData, true);
        $platform = 'wxapp';
        $result = [
            'openid'        => $openid,
            'userinfo'      => [
                'nickname' => $userInfo['nickName'],
            ],
        ];
        $extend = ['gender' => $userInfo['gender'], 'nickname' => $userInfo['nickName'], 'avatar' => $userInfo['avatarUrl']];
        
        // 第三方登录入库
        $ret = Service::connect($platform, $result, $extend);
        if ($ret) {
            //登录成功后的用户数据操作
            $auth = Auth::instance();

            $this->success("微信授权成功", ['userInfo' => $auth->getUserinfo()]);
        } else {
            $this->error("微信授权失败");
        }
    }

    /**
     * 小程序登录接口
     * @ApiSummary  (小程序登录接口)
     * @ApiMethod   (POST)
     * @ApiParams   (name="code", type="string", required=true, description="微信获取的code")
     * @ApiReturnParams   (name="openid", type="string", required=true, description="openid")
     * @ApiReturnParams   (name="http_result", type="string", required=true, description="wx登录返回的数据")
     */
    public function miniapplogin()
    {
        $config = get_addon_config('third');    
        $config = $config['wechat'];

        $code = $this->request->post("code");
        if (!$code) {
            $this->error("参数不正确");
        }
        
        $params = [
            'appid'      => $config['app_id'],
            'secret'     => $config['app_secret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];

        $http_result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');

        if ($http_result['ret']) {
            $json = (array)json_decode($http_result['msg'], true);
            if (isset($json['openid'])) {
                
                $platform = 'wxapp';
                $result = [
                    'openid'        => $json['openid'],
                    'access_token'  => $json['session_key'],
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                ];
                // 第三方登录入库
                // 在user表创建一条新用户数据
                $ret = Service::connect($platform, $result);

                if ($ret) {
                    //登录成功后的用户数据操作
                    $auth = Auth::instance();

                    $this->success("登录成功", ['http_result' => $json,'openid'=>$json['openid'],'token' => $auth->getUserinfo()['token']]);
                } else {
                    $this->error("连接失败");
                }
            } else {
                $this->error("登录失败",$http_result['msg']);
            }
        }

        return;
    }

      /**
     * 修改用户信息(包含银行卡信息)
     * @param string $avatar
     * @param string $nickname
     * @param string $bank_name 开户姓名
     * @param string $card_number 银行卡号
     * @param string $account_bank 开户行
     * @param string $id_num 身份证号码
     * @param string $bank_phone 预留手机
     */
    public function edit(){
        $user = $this->auth->getUser();
        $params = input();
        $avatar = input('avatar');
        $nickname = input('nickname');
     
        if($avatar){
            $user->avatar = $avatar;
        }
        if($nickname){
            $user->nickname = $nickname;
        }
        if($params['bank_name']){
            $user->bank_name = $params['bank_name'];
        }
        if($params['card_number']){
            $user->card_number = $params['card_number'];
        }
        if($params['account_bank']){
            $user->account_bank = $params['account_bank'];
        }
        if($params['id_num']){
            $user->id_num = $params['id_num'];
        }
        if($params['bank_phone']){
            $user->bank_phone = $params['bank_phone'];
        }
        $user->save();
        $this->success('修改成功');
    }
    
    /**
     * 会员信息(提成余额total_price，今日核销订单数量today_count,今日佣金额today_sum)
     * @ApiMethod   (GET)
     */
    public function index()
    {
        $userInfo = $this->auth->getUserinfo();
        $region = Db::name('region')->where('user_id',$userInfo['id'])->find();

        $userInfo['total_price'] = $region['income'];

        $today_count_sql = "select count(*) as num from `fa_income_detail` Where  date_format(from_unixtime(createtime),'%Y-%m-%d') = date_format(now(),'%Y-%m-%d')";
        $today_sum_sql = "select sum(income) as total_price from `fa_income_detail` Where  date_format(from_unixtime(createtime),'%Y-%m-%d') = date_format(now(),'%Y-%m-%d')";

        $todaysql_count = Db::query($today_count_sql);
        $todaysql_sum = Db::query($today_sum_sql);
        
        $userInfo['today_count'] = $todaysql_count[0]['num'];
        $userInfo['today_sum'] = $todaysql_sum[0]['total_price'];
        
        $this->success('会员信息', $userInfo);
    }
 
    /**
    * 收入明细 watch字段：1是收入，0是提现
    * 
    **/
    public function my_income_list(){
        $userInfo = $this->auth->getUserinfo();
        $return = IncomeDetail::where(['user_id'=>$userInfo['id']])->order('createtime desc')->find();

        $this->success('收入明细',$return);
    }

    /**
    * 佣金提现 只需要传提现金额
    * @param string $price 提现金额
    **/
    public function withdraw(){
        $params = input();
        $userInfo = $this->auth->getUserinfo();

        $region = region::where('user_id',$userInfo['id'])->find();
        if($params['price']>$region['income'])$this->error('提现金额大于佣金余额');

        $income_insert['user_id'] = $userInfo['id'];
        $income_insert['status'] = 0;
        $income_insert['watch'] = 0;
        $income_insert['income'] = $params['price'];
        $IncomeDetail = new IncomeDetail();
        $res = $IncomeDetail->save($income_insert);
        $res2 = $region->setDec('income',$params['price']);

        if($res&&$res2)$this->success('提现成功');

    }   

    /**
     * 获取我的同城列表
     * @ApiSummary  
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/my/my_manuscript)
     */
    public function my_manuscript()
    {
        $user = $this->auth->getUser();
        $my_manuscript = Db::name('manuscript')->where(['user_id'=>$user->id])->field("id,title,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->order('createtime desc')->select();

        $this->success('获取我的同城列表',$my_manuscript);
    }

    /**
     * 获取我的收藏列表（两种情况，要么有数据，要么就提示列表为空）
     * @ApiSummary  
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/my/my_collect)
     */
    public function my_collect()
    {
        $user = $this->auth->getUser();
        $collect = Db::name('collect')->where(['user_id'=>$user->id])->value('collect');
        $collect = json_decode($collect,true);
        if(empty($collect))$this->error('列表为空');
        $collect = implode(',', $collect);
        $list = Db::name('manuscript')->where('id','in',$collect)->field("id,title,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->order('createtime desc')->select();
        $this->success('获取我的收藏列表（两种情况，要么有数据，要么就提示列表为空）',$list);
    }



}
